package com.cmnit.service;

import com.cmnit.utils.DateUtils;
import com.cmnit.utils.HiveUtils;
import com.cmnit.utils.MySqlUtils;

import java.util.List;

public class HiveService {
    /**
     * 获取目标表的指定账期增量数据
     *
     * @param time 账期时间
     */
    public static void getTableCount(String time) {
        // 获取账期时间
        String acctTime = DateUtils.getAcctTime(time);

        // 结果表（Mysql）段
        String tableName = "datalake_workspace_hivetablecount";
        String updateField = "tablename,count,time";

        // 获取配置文件表（Hive）中的数据
        String sql = "select source_name, status from DIM.DIM_DATALAKE_DISPLAY where filed_sign = 'table'";
        String resultField = "source_name,status";
        List<String> tableList = HiveUtils.query(sql, resultField);
        for (String info : tableList) {
            String[] tableValue = info.split(",");
            String count = null;
            String table = tableValue[0];
            String status = tableValue[1];
            try {
                if ("hour".equals(status)) {
                    count = getCountByHour(table, time);
                } else if ("day".equals(status)) {
                    count = getCountByDay(table, time.substring(0, 10));
                }
                // Mysql结果表写入字段的值
                String valuesField = table + "," + count + "," + acctTime;
                MySqlUtils.insert(tableName, updateField, valuesField);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取小时分区表
     *
     * @param table    表名
     * @param acctTime 账期时间
     */
    public static String getCountByHour(String table, String acctTime) {
        String sql = "select count(*) count from " + table + " where year = ? and month = ? and day = ? and hour = ? limit 1";
        String resultField = "count";
        List<String> res = HiveUtils.query(sql, acctTime, resultField);
        return res.get(0);
    }

    /**
     * 获取日分区表
     *
     * @param table    表名
     * @param acctTime 账期时间
     */
    public static String getCountByDay(String table, String acctTime) {
        String sql = "select count(*) count from " + table + " where year = ? and month = ? and day = ? limit 1";
        String resultField = "count";
        List<String> res = HiveUtils.query(sql, acctTime, resultField);
        return res.get(0);
    }
}
